package util;

import java.util.*;
import org.junit.Test;

public class BracketUtils {

    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    public static int[] to1DArray(String input) {
        input = input.trim();
        input = input.substring(1, input.length() - 1);
        if (input.length() == 0) {
            return new int[0];
        }
    
        String[] parts = input.split(",");
        int[] output = new int[parts.length];
        for(int index = 0; index < parts.length; index++) {
            String part = parts[index].trim();
            output[index] = Integer.parseInt(part);
        }
        return output;
    }

    public static int[][] to2DArray(String str) {
        str = str.substring(1, str.length() - 1);
        str = str.replace(" ", "");
        String[] ss = str.split("],");
        for (int i = 0; i < ss.length; i++) {
            String s = ss[i].substring(1);
            s = s.replace("[", "");
            s = s.replace("]", "");
            ss[i] = s;
        }

        List<List<Integer>> nums = new ArrayList<>();
        for (String s : ss) {
            String[] strs = s.split(",");
            List<Integer> list = new ArrayList<>();
            for (String s1: strs) {
                list.add(Integer.parseInt(s1));
            }
            nums.add(list);
        }

        int[][] res = new int[nums.size()][];
        int idx = 0;
        for (List<Integer> list: nums) {
            res[idx++] = list.stream().mapToInt(Integer::valueOf).toArray();
        }
        return res;

    }

    @Test
    public void test() {
        int[][] res = BracketUtils.to2DArray("[[1,2,3],[4,5,6],[7,8,9]]");
        for (int i = 0; i < res.length; i++) {
            System.out.println(Arrays.toString(res[i]));
        }
     }

     public static void printArray(int[] nums) { 
        System.out.println(Arrays.toString(nums));   
     }

     public static void printArray(int[][] nums) {
         for (int i = 0; i < nums.length; i++) {
             System.out.println(Arrays.toString(nums[i]));
         }
     }

     public static void printArray(boolean[][] nums) {
        for (int i = 0; i < nums.length; i++) {
            System.out.println(Arrays.toString(nums[i]));
        }
    }
}

